from typing import Dict, Any, List
import json
import os
from datetime import datetime
from .base_formatter import BaseFormatter

class JSONFormatter(BaseFormatter):
    """JSON报告格式化器"""
    
    def format_report(self, results: List[Dict[str, Any]], scan_info: Dict[str, Any]) -> None:
        """生成JSON格式的报告
        
        Args:
            results: 扫描结果列表
            scan_info: 扫描信息字典
        """
        filename = os.path.join(self.output_dir, 'scan_report.json')
        
        # 准备报告数据
        report = {
            'scan_info': {
                'start_time': self._format_timestamp(scan_info['start_time']),
                'end_time': self._format_timestamp(scan_info['end_time']),
                'total_hosts': scan_info['total_hosts'],
                'total_ports': scan_info['total_ports'],
                'open_ports': len([r for r in results if r['status'] == 'open'])
            },
            'results': []
        }
        
        # 处理扫描结果
        for result in sorted(results, key=lambda x: (x['target'], x['port'])):
            result_data = {
                'target': result['target'],
                'port': result['port'],
                'status': result['status'],
                'service': result['service'] or "未知",
                'latency': f"{result['latency']}ms" if result['latency'] else "N/A"
            }
            
            # 添加服务详细信息
            if result['service_info'] and result['status'] == 'open':
                service_details = self._get_service_details(result['service_info'])
                result_data['service_details'] = service_details
                
                # 保留原始服务信息以供其他用途
                result_data['raw_service_info'] = result['service_info']
            
            report['results'].append(result_data)
        
        # 写入文件
        self._write_file(
            filename,
            json.dumps(report, indent=2, ensure_ascii=False),
            encoding='utf-8'
        ) 